//
//  SearchResultsViewController.swift
//  WNLockDemo
//
//  Created by 裴威 on 31/08/2018.
//  Copyright © 2018 wunu. All rights reserved.
//

import UIKit
import CoreBluetooth
import PKHUD

class SearchResultsViewController: UIViewController {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
    @IBOutlet weak var searchBleTextLabel: UILabel!
    
    private var isSearching: Bool = false {
        didSet {
            if isSearching {
                bleM.startScan()
                searchBleTextLabel.text = "正在搜索..."
                activityIndicatorView.isHidden = false
                activityIndicatorView.startAnimating()
            } else {
                bleM.stopScan()
                searchBleTextLabel.text = "搜索蓝牙设备"
                activityIndicatorView.stopAnimating()
                activityIndicatorView.isHidden = true
            }
            
        }
    }
    private var bleM: BLEFacade!
    fileprivate var devices: [BleDevice] = [] {
        didSet {
            tableView.reloadData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configureNavigationBarBack()
        startSearchBleLock()
    }
    private func startSearchBleLock() {
        let config = BLEConfigure(serviceUUID: CBUUID(string: "FFF0"), readUUID: CBUUID(string: "FFF7"), writeUUID: CBUUID(string: "FFF6"))
        bleM = BLEFacade(configure: config)
        bleM.delegate = self
        
    }

    /// 开始搜索蓝牙设备
    @IBAction func handleSearchBleDeviceEvent(_ sender: UITapGestureRecognizer) {
        isSearching = !isSearching
        sender.view?.setNeedsLayout()
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        bleM.stopScan()
        switch sender {
        case let cell as UITableViewCell:
            let indexPath = tableView.indexPath(for: cell)!
            switch segue.destination {
            case let vc as LockBindViewController:
                vc.bleM = bleM
                vc.device = devices[indexPath.row]
            default:
                break
            }
        default:
            break
        }
    }

}

// MARK: - UITableViewDataSource
extension SearchResultsViewController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return devices.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let device = devices[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "ResultCell") as! SearchLockResultTableViewCell
        cell.nameLabel.text = "智能锁: \(device.name!)"
        cell.rssiLabel.text = "信号强度: \(device.rssi)"
        return cell
    }
    
    
}

// MARK: - UITableViewDelegate
extension SearchResultsViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}

// MARK: - BLELockDelegate
extension SearchResultsViewController: BLELockDelegate {
    func didDiscoverDevice(_ device: BleDevice) {
        if let name = device.name, name.contains("WSL_") {
            if let index = (devices.index { $0.name ?? "" == name}) {
                devices[index] = device
            } else {
                devices.append(device)
            }
        }
    }
    func didUpdateState(_ state: CBCentralManagerState) {
        if state == .poweredOff {
            HUD.flash(.label("未打开蓝牙"), delay: 1.5)
        } else {
            bleM.startScan()
        }
    }
}
